const user = require('../data/user');
const Code = require('../data/unCode')
module.exports = (req, res, next) => {
  const un = req.body.username;
  const pw = req.body.password;
  const tel = req.body.tel;
  const code = req.body.code;
  console.log(code)
  Code.find({ uncode: code }).then(cd => {
    if (cd.length > 0) {
      res.send({
        state: 0,
        msg: '验证码不对'
      })
    } else {



      if (!un) res.send('注册失败用户名为空')
      if (!pw) res.send('注册失败密码为空')
      user.find({ username: un }).then((data) => {
        if (data.length > 0) {
          res.send({
            state: 0,
            msg: '用户名重复'
          })
        } else {
          user.find({ tel: tel }).then((data) => {
            console.log(data)
            if (data.length > 0) {
              res.send({
                state: 0,
                msg: '该手机号已被注册',
                data
              })
            } else {


              // 删除验证码
              // Code.deleteMany().then(res => {
              //   return Code.find()
              // }).then(res => {
              //   console.log('验证码数据库', res)
              // })
              Code.deleteOne({ unCode: tel + ',' + code }).then(res => {
                return Code.find()
              }).then(res => {
                console.log(res)
              })


              // 没读到，向数据库新增
              user.insertMany({
                uId: Math.random() + "" + Date.now(),
                username: un,
                password: pw,
                tel: tel,
                nickName: "用户" + random(),
                age: 0,
                sex: "",
                regTime: Date.now(),
                power: 0
              }).then(() => {
                res.send({
                  state: 1,
                  msg: "注册成功"
                });
              })
            }
          })
        }
      })
    }
  })


}
function random() {
  return ((Math.random() * 1000000000000) + "").substr(2, 5)
}